import React, { useEffect, useMemo, useState } from 'react';
import {
  Card,
  Row,
  Col,
  Avatar,
  Button,
  Space,
  Descriptions,
  Steps,
  Alert,
  Modal,
  Form,
  Input,
  Select,
  Upload,
  message,
} from 'antd';
import { SettingOutlined, EditOutlined } from '@ant-design/icons';

const { Step } = Steps;

export default function AccountConfiguration() {
  // 基础信息（模拟）
  const [userInfo, setUserInfo] = useState({
    avatar: 'https://avatars.githubusercontent.com/u/9919?s=200&v=4',
    account: 'merchant_001',
    mobile: '13800000000',
    nickName: '商户A',
    email: 'merchant@example.com',
    createTime: '2024-01-01 10:00:00',
    expireTime: '2025-01-01 10:00:00',
    businessWallet: { printPoints: 1200 },
    id: 1,
  });

  // 公众号 / PayPal / 银行卡信息（模拟）
  const [gzhInfo, setGzhInfo] = useState({ gzhName: '', appId: '', appSecret: '', templateId: '' });
  const [paypalInfo, setPaypalInfo] = useState({ clientId: '', secret: '' });
  const [yhkInfo, setYhkInfo] = useState({
    // 审批与签约流程状态（参考 merchant-end-111）
    orderStatus: 'P3004', // P3003 冻结；P3004 已开户
    authStatus: 'R4004', // R4002 待认证；R4003 认证失败；R4004 已认证
    approveStatus: 'P1000', // P2000 审批失败；P1000 审批通过
    signStatus: 0, // 0 未签约；-1 失败；1 成功
  });

  // 步骤条状态
  const [stepsCurrent, setStepsCurrent] = useState(1);
  const [stepsStatus, setStepsStatus] = useState('process'); // wait | process | finish | error

  // 模态框控制
  const [userModalOpen, setUserModalOpen] = useState(false);
  const [gzhModalOpen, setGzhModalOpen] = useState(false);
  const [paypalModalOpen, setPaypalModalOpen] = useState(false);
  const [joinPayModalOpen, setJoinPayModalOpen] = useState(false);
  const [signModalOpen, setSignModalOpen] = useState(false);
  const [signHtml, setSignHtml] = useState('');

  // 表单
  const [userForm] = Form.useForm();
  const [gzhForm] = Form.useForm();
  const [paypalForm] = Form.useForm();
  const [joinPayForm] = Form.useForm();

  // 银行账户类型 / 商户类型
  const accountTypeArr = useMemo(() => [
    { label: '个人账户', value: 1 },
    { label: '对公账户', value: 4 },
  ], []);
  const merchantArr = useMemo(() => [
    { value: 10, label: '个人' },
    { value: 11, label: '企业' },
    { value: 12, label: '个体工商户' },
  ], []);

  // 初始化（模拟获取）
  useEffect(() => {
    // 模拟：更新步骤条
    updateTimeLine(yhkInfo);
  }, []);

  const updateTimeLine = (info) => {
    // 默认第一步
    let current = 1;
    let status = 'process';

    // step1 开户
    if (!info.orderStatus) {
      current = 1;
      status = 'wait';
    } else {
      if (info.orderStatus === 'P3003') status = 'error';
      if (info.orderStatus === 'P3004') current = 2; // 进入下一步
    }

    // step2 认证
    if (!info.authStatus || info.authStatus === 'P4001') {
      // 未配置
    } else {
      if (info.authStatus === 'R4002') status = 'wait';
      if (info.authStatus === 'R4003') status = 'error';
      if (info.authStatus === 'R4004') current = 3;
    }

    // step3 审批
    if (!info.approveStatus || info.approveStatus === 'P0001') {
      // 未配置
    } else {
      if (info.approveStatus === 'P2000') status = 'error';
      if (info.approveStatus === 'P1000') status = 'finish';
    }

    setStepsCurrent(current);
    setStepsStatus(status);
  };

  // 触发编辑资料
  const insertUserInfo = () => {
    userForm.setFieldsValue({
      nickName: userInfo.nickName,
      password: '',
      confirmPassword: '',
      mobile: userInfo.mobile,
      email: userInfo.email,
    });
    setUserModalOpen(true);
  };

  const handleSaveUser = async () => {
    const values = await userForm.validateFields().catch(() => null);
    if (!values) return false;
    if (values.password && values.password !== values.confirmPassword) {
      message.warning('两次输入的密码不一致');
      return false;
    }
    setUserInfo((prev) => ({
      ...prev,
      nickName: values.nickName,
      mobile: values.mobile,
      email: values.email,
    }));
    message.success('资料已更新');
    setUserModalOpen(false);
  };

  // 触发配置公众号
  const handlerInsertGzh = () => {
    gzhForm.setFieldsValue(gzhInfo);
    setGzhModalOpen(true);
  };
  const handleSaveGzh = async () => {
    const values = await gzhForm.validateFields().catch(() => null);
    if (!values) return false;
    setGzhInfo(values);
    message.success('公众号信息已保存');
    setGzhModalOpen(false);
  };

  // 触发配置 paypal
  const handlerInsertPaypal = () => {
    paypalForm.setFieldsValue(paypalInfo);
    setPaypalModalOpen(true);
  };
  const handleSavePaypal = async () => {
    const values = await paypalForm.validateFields().catch(() => null);
    if (!values) return false;
    setPaypalInfo(values);
    message.success('PayPal信息已保存');
    setPaypalModalOpen(false);
  };

  // 触发配置银行卡（JoinPay）
  const handlerInsertJoinPay = () => {
    joinPayForm.setFieldsValue(yhkInfo);
    setJoinPayModalOpen(true);
  };
  const handleSaveJoinPay = async () => {
    const values = await joinPayForm.validateFields().catch(() => null);
    if (!values) return false;
    const next = { ...yhkInfo, ...values };
    setYhkInfo(next);
    updateTimeLine(next);
    message.success('银行卡信息已保存');
    setJoinPayModalOpen(false);
  };

  // 上传（模拟）
  const customUpload = (options, name) => {
    const { file, onSuccess, onError } = options;
    const reader = new FileReader();
    reader.onload = () => {
      const url = reader.result;
      setYhkInfo((prev) => ({ ...prev, [name]: url }));
      onSuccess && onSuccess({ url });
      message.success('图片已上传');
    };
    reader.onerror = () => {
      onError && onError(new Error('上传失败'));
    };
    reader.readAsDataURL(file);
  };

  // 签约
  const handlerSign = async () => {
    if (!signHtml) {
      // 模拟签约内容
      setSignHtml('<h3 style="margin:0 0 12px">签约内容</h3><p>这是模拟的签约协议内容。点击确定即视为同意签约。</p>');
    }
    setSignModalOpen(true);
  };
  const handleAgreeSign = () => {
    setYhkInfo((prev) => ({ ...prev, signStatus: 1 }));
    message.success('签约成功');
    setSignModalOpen(false);
  };

  // 警示区域文案
  const renderSignAlert = () => {
    if (yhkInfo.signStatus === 1) {
      return (
        <Alert type="success" message="已签约" description={<span>您的账户已完成签约。</span>} />
      );
    }
    if (yhkInfo.signStatus === -1) {
      return (
        <Alert
          type="error"
          message="签约失败"
          description={
            <span>
              请检查资料后重新签约，
              <a onClick={handlerSign}>点击重新签约</a>
            </span>
          }
        />
      );
    }
    // 默认：未签约
    return (
      <Alert
        type="warning"
        message="未签约"
        description={
          <span>
            {yhkInfo.approveStatus === 'P1000' ? (
              <a onClick={handlerSign}>去签约</a>
            ) : (
              '请先完成开户与审批流程'
            )}
          </span>
        }
      />
    );
  };

  return (
    <div style={{ padding: 16 }}>
      {/* 资料与操作 */}
      <Card style={{ marginBottom: 16 }}>
        <Row align="middle" gutter={[16, 16]}>
          <Col span={24}>
            <Space align="center">
              <span style={{ minWidth: 100, fontSize: 20 }}>账户资料</span>
              <Button type="primary" size="small" icon={<EditOutlined />} onClick={insertUserInfo}>
                编辑资料
              </Button>
            </Space>
          </Col>
        </Row>
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={6} md={5} lg={4} xl={3} style={{ display: 'flex', justifyContent: 'center' }}>
            <Avatar shape="square" size={100} src={userInfo.avatar} style={{ borderRadius: 10 }} />
          </Col>
          <Col xs={24} sm={18} md={19} lg={20} xl={21}>
            <Descriptions bordered column={2} size="small">
              <Descriptions.Item label="账户">{userInfo.account}</Descriptions.Item>
              <Descriptions.Item label="手机号">{userInfo.mobile}</Descriptions.Item>
              <Descriptions.Item label="昵称">{userInfo.nickName}</Descriptions.Item>
              <Descriptions.Item label="邮箱">{userInfo.email}</Descriptions.Item>
              <Descriptions.Item label="创建时间">{userInfo.createTime}</Descriptions.Item>
              <Descriptions.Item label="过期时间">{userInfo.expireTime}</Descriptions.Item>
              <Descriptions.Item label="打印积分">
                {userInfo.businessWallet?.printPoints}
              </Descriptions.Item>
            </Descriptions>
          </Col>
        </Row>
      </Card>

      {/* 公众号配置 */}
      <Card style={{ marginBottom: 16 }}>
        <Space align="center">
          <span style={{ minWidth: 100, fontSize: 20 }}>公众号配置{gzhInfo.gzhName ? `（${gzhInfo.gzhName}）` : ''}</span>
          <Button type="primary" size="small" onClick={handlerInsertGzh}>配置公众号</Button>
        </Space>
      </Card>

      {/* 银行卡配置 + 步骤条 + 警示 */}
      <Card style={{ marginBottom: 16 }}>
        <Space align="center" style={{ marginBottom: 12 }}>
          <span style={{ minWidth: 100, fontSize: 20 }}>银行卡配置（JoinPay）</span>
          <Button type="primary" size="small" onClick={handlerInsertJoinPay}>配置银行卡</Button>
        </Space>
        <div style={{ maxWidth: 800, marginTop: 8 }}>
          <Steps current={stepsCurrent} status={stepsStatus}>
            <Step title="开户" />
            <Step title="认证" />
            <Step title="审批" />
          </Steps>
        </div>
        <div style={{ maxWidth: 600, marginTop: 16 }}>{renderSignAlert()}</div>
      </Card>

      {/* PayPal 配置 */}
      <Card style={{ marginBottom: 16 }}>
        <Space align="center">
          <span style={{ minWidth: 100, fontSize: 20 }}>PayPal配置</span>
          <Button type="primary" size="small" onClick={handlerInsertPaypal}>配置PayPal</Button>
        </Space>
      </Card>

      {/* 编辑资料 Modal */}
      <Modal
        title="编辑资料"
        open={userModalOpen}
        onCancel={() => setUserModalOpen(false)}
        onOk={handleSaveUser}
        okText="保存"
        width={480}
      >
        <Form form={userForm} layout="vertical">
          <Form.Item name="nickName" label="昵称" rules={[{ required: true, message: '请输入昵称' }]}> 
            <Input />
          </Form.Item>
          <Form.Item name="password" label="新密码">
            <Input.Password />
          </Form.Item>
          <Form.Item name="confirmPassword" label="确认密码">
            <Input.Password />
          </Form.Item>
          <Form.Item name="mobile" label="手机号" rules={[{ pattern: /^\d{11}$/, message: '请输入11位手机号' }]}> 
            <Input />
          </Form.Item>
          <Form.Item name="email" label="邮箱" rules={[{ type: 'email', message: '邮箱格式不正确' }]}> 
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      {/* 公众号配置 Modal */}
      <Modal
        title="配置公众号"
        open={gzhModalOpen}
        onCancel={() => setGzhModalOpen(false)}
        onOk={handleSaveGzh}
        okText="保存"
        width={600}
      >
        <Form form={gzhForm} layout="vertical">
          <Form.Item name="gzhName" label="公众号名称" rules={[{ required: true, message: '请输入公众号名称' }]}> 
            <Input />
          </Form.Item>
          <Form.Item name="appId" label="appid" rules={[{ required: true, message: '请输入appid' }]}> 
            <Input />
          </Form.Item>
          <Form.Item name="appSecret" label="secret" rules={[{ required: true, message: '请输入secret' }]}> 
            <Input />
          </Form.Item>
          <Form.Item name="templateId" label="模板ID" rules={[{ required: true, message: '请输入模板ID' }]}> 
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      {/* PayPal 配置 Modal */}
      <Modal
        title="配置PayPal"
        open={paypalModalOpen}
        onCancel={() => setPaypalModalOpen(false)}
        onOk={handleSavePaypal}
        okText="保存"
        width={600}
      >
        <Form form={paypalForm} layout="vertical">
          <Form.Item name="clientId" label="clientId" rules={[{ required: true, message: '请输入clientId' }]}> 
            <Input />
          </Form.Item>
          <Form.Item name="secret" label="secret" rules={[{ required: true, message: '请输入secret' }]}> 
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      {/* 银行卡配置 Modal */}
      <Modal
        title="配置银行卡（JoinPay）"
        open={joinPayModalOpen}
        onCancel={() => setJoinPayModalOpen(false)}
        onOk={handleSaveJoinPay}
        okText="保存"
        width={800}
      >
        <Form form={joinPayForm} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="loginName" label="登录名称(邮箱)" rules={[{ required: true, message: '请输入登录名称' }]}> 
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="altMchName" label="商户名称" rules={[{ required: true, message: '请输入商户名称' }]}> 
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="bankAccountType" label="银行账户类型" rules={[{ required: true, message: '请选择账户类型' }]}> 
                <Select options={accountTypeArr} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="altMerchantType" label="商户类型" rules={[{ required: true, message: '请选择商户类型' }]}> 
                <Select options={merchantArr} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="legalPerson" label="法人姓名" rules={[{ required: true, message: '请输入法人姓名' }]}> 
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="idCardNo" label="身份证号" rules={[{ required: true, message: '请输入身份证号' }]}> 
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="phoneNo" label="预留手机号" rules={[{ required: true, message: '请输入预留手机号' }]}> 
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="bankAccountNo" label="银行卡号" rules={[{ required: true, message: '请输入银行卡号' }]}> 
                <Input />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="身份证正面">
                <Upload.Dragger
                  customRequest={(opts) => customUpload(opts, 'cardPositive')}
                  showUploadList={false}
                  accept=".png,.jpg,.jpeg"
                  style={{ height: 120 }}
                >
                  {yhkInfo.cardPositive ? (
                    <img alt="cardPositive" src={yhkInfo.cardPositive} style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
                  ) : (
                    <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>点击或拖拽上传</div>
                  )}
                </Upload.Dragger>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="身份证反面">
                <Upload.Dragger
                  customRequest={(opts) => customUpload(opts, 'cardBack')}
                  showUploadList={false}
                  accept=".png,.jpg,.jpeg"
                  style={{ height: 120 }}
                >
                  {yhkInfo.cardBack ? (
                    <img alt="cardBack" src={yhkInfo.cardBack} style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
                  ) : (
                    <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>点击或拖拽上传</div>
                  )}
                </Upload.Dragger>
              </Form.Item>
            </Col>
          </Row>

          {/* 条件字段 */}
          {(joinPayForm.getFieldValue('altMerchantType') ?? yhkInfo.altMerchantType) !== 10 && (
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item name="licenseNo" label="营业执照号" rules={[{ required: true, message: '请输入营业执照号' }]}> 
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="营业执照">
                  <Upload.Dragger
                    customRequest={(opts) => customUpload(opts, 'tradeLicence')}
                    showUploadList={false}
                    accept=".png,.jpg,.jpeg"
                    style={{ height: 120 }}
                  >
                    {yhkInfo.tradeLicence ? (
                      <img alt="tradeLicence" src={yhkInfo.tradeLicence} style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
                    ) : (
                      <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>点击或拖拽上传</div>
                    )}
                  </Upload.Dragger>
                </Form.Item>
              </Col>
            </Row>
          )}

          {(joinPayForm.getFieldValue('bankAccountType') ?? yhkInfo.bankAccountType) === 4 && (
            <Form.Item name="bankChannelNo" label="开户行联行号" rules={[{ required: true, message: '请输入联行号' }]}> 
              <Input />
            </Form.Item>
          )}

          {(joinPayForm.getFieldValue('altMerchantType') ?? yhkInfo.altMerchantType) !== 10 && (
            <Form.Item label="开户许可证">
              <Upload.Dragger
                customRequest={(opts) => customUpload(opts, 'openAccountLicence')}
                showUploadList={false}
                accept=".png,.jpg,.jpeg"
                style={{ height: 120 }}
              >
                {yhkInfo.openAccountLicence ? (
                  <img alt="openAccountLicence" src={yhkInfo.openAccountLicence} style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
                ) : (
                  <div style={{ height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>点击或拖拽上传</div>
                )}
              </Upload.Dragger>
            </Form.Item>
          )}
        </Form>
      </Modal>

      {/* 签约 Modal */}
      <Modal
        title="签约"
        open={signModalOpen}
        onCancel={() => setSignModalOpen(false)}
        onOk={handleAgreeSign}
        okText="同意并签约"
        width={600}
      >
        <div dangerouslySetInnerHTML={{ __html: signHtml }} />
      </Modal>
    </div>
  );
}